package com.jsmile.cloud.authc.sys.repo;

import java.util.Date;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsmile.cloud.authc.api.req.ReqSysUserRegister;
import com.jsmile.cloud.authc.api.res.ResSysUser;
import com.jsmile.cloud.authc.sys.dao.SysUserDao;
import com.jsmile.cloud.authc.sys.model.SysUser;
import com.jsmile.mall.api.enums.SfEnum;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 为了薪资破万，还是睡一会儿吧...!
 * @date 2020年10月16日 02:46:20
 */
@Service
@Slf4j
@Transactional(readOnly = false, rollbackFor = Exception.class)
public class SysUserRepository extends ServiceImpl<SysUserDao, SysUser> {

    public ResSysUser register(ReqSysUserRegister reqSysUserRegister) {
        ResSysUser userVo = this.baseMapper.findByUsernameAndShopId(reqSysUserRegister.getUserName(), reqSysUserRegister.getTenantId(), reqSysUserRegister.getShopId(),
            reqSysUserRegister.getUserType(), SfEnum.F.getValue());
        if (null == userVo) {
            SysUser sysUser = BeanUtil.toBean(reqSysUserRegister, SysUser.class);
            sysUser.setCreateTime(new Date());
            sysUser.setPassword(new BCryptPasswordEncoder().encode(reqSysUserRegister.getPassword()));
            this.saveOrUpdate(sysUser);
            userVo = this.baseMapper.findByUsernameAndShopId(reqSysUserRegister.getUserName(), reqSysUserRegister.getTenantId(), reqSysUserRegister.getShopId(),
                reqSysUserRegister.getUserType(), SfEnum.F.getValue());
        } else {
            SysUser sysUser = BeanUtil.toBean(reqSysUserRegister, SysUser.class);
            sysUser.setUpdateTime(new Date());
            sysUser.setId(userVo.getId());
            this.saveOrUpdate(sysUser);
        }
        return userVo;
    }
}
